<template>
  <div>
    <div class="relate-dragram-box">
      <div class="dragram-item">
        <div class="dragram-item-top">
          
          <div class="load-cont-box">
            <div class="load-cont">
                <div class="filter-cont" @click="dowmImage">
                    <div class="img-wrap">
                        <el-image class="load-img show-img" :src="loadImg" fit="contain" />
                        <el-image class="load-img hover-img" :src="loadhoverImg" fit="contain" />
                        <el-image class="load-img active-img" :src="loadactiveImg" fit="contain" />
                    </div>
                </div>
            </div>
          </div>
        </div>
        <div id="uiCahrt">
          <div class="range-box">
            <el-slider v-model="graphRange" range :max="maxRange" @input="changeSlider" :step="0.00001"/>
          </div>
          <div class="dragram-item-bott">
            <div class="dragram-chart"> 
              <uiEchart style="width:800px;height:360px;" class="chart-network" v-show="!loadingNetWork && !noDataFlag" :config="chartOpt"  ref="graphCanvas" :vt="echartoptVt"/>
              <div class="no-data-box" v-show="loadingNetWork">
                  <img :src="Loading"/>
                  <div class="no-data-txt" v-lang="{lang: controlSto.language, lgid: '-131'}">loading...</div>
              </div>
              <div class="no-data-box" v-show="!loadingNetWork && noDataFlag">
                  <img :src="NodtaPng"/>
                  <div class="no-data-txt" v-lang="{lang: controlSto.language, lgid: '-118'}">暂无数据</div>
              </div>
            </div>
            <div class="dragram-legend" v-show="!loadingNetWork && !noDataFlag">
              <div class="legen-list" v-for="(item, index) in diagramLenList" :key="item.id + index">
                <div class="legen-item" :class="{'legen-item-dis' : !item.isShow}" @click="changeShow(item, index)">
                  <img v-if="item.source.code == 1 " :src="prescriptionlegIcon" class="legen-item-ltImg"/>
                  <img v-if="item.source.code == 2 " :src="HerbLegIcon" class="legen-item-ltImg"/>
                  <img v-if="item.source.code == 3 " :src="ingredientlegIcon" class="legen-item-ltImg"/>
                  <img v-if="item.source.code == 4 " :src="deseaselegIcon" class="legen-item-ltImg"/>
                  <span
                    class="legen-item-wz"
                    :class="{ 'col1' : item.source.code == 1, 'col2' : item.source.code == 2 , 'col3' : item.source.code == 3, 'col4': item.source.code == 4 }"
                  >{{ item.source.name }}</span>
                  <div class="legen-center">
                    <img :src="lRDoubleRoute" width="33"/>
                  </div>
                  <img v-if="item.target.code == 1 " :src="prescriptionlegIcon" class="legen-item-ltImg"/>
                  <img v-if="item.target.code == 2 " :src="HerbLegIcon" class="legen-item-ltImg"/>
                  <img v-if="item.target.code == 3 " :src="ingredientlegIcon" class="legen-item-ltImg"/>
                  <img v-if="item.target.code == 4 " :src="deseaselegIcon" class="legen-item-ltImg"/>
                  <span
                    class="legen-item-wz"
                    :class="{ 'col1' : item.target.code == 1, 'col2' : item.target.code == 2 , 'col3' : item.target.code == 3, 'col4': item.target.code == 4 }"
                  >{{ item.target.name }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, reactive, toRefs, ref, watch, nextTick } from 'vue'
import uiEchart from '@/components/ui-echart.vue'
import loadImg from '@/assets/img/load.png'
import loadhoverImg from '@/assets/img/load-hover.png'
import loadactiveImg from '@/assets/img/load-active.png'
import HerbLegIcon from '@/assets/img/herblegIcon.png'
import ingredientlegIcon from '@/assets/img/ingredientlegIcon.png'
import deseaselegIcon from '@/assets/img/deseaselegIcon.png'
import prescriptionlegIcon from '@/assets/img/prescriptionlegIcon.png'
import lRDoubleRoute from '@/assets/img/lRDoubleRoute.png'
import html2canvas from 'html2canvas';
import Loading from '@/assets/img/loading.gif'
import NodtaPng from '@/assets/img/noData.png'
// import { graph } from '@/utils/datagraph'
import { debounce, cloneDeep, concat, filter, uniqBy } from 'lodash'
// import { calculateEquilateralTriangleCoords, saveImageWithWhiteBackground, saveImgDiv } from '@/utils/util'
import { controlStore } from '@/stores/control'
const props = defineProps({
  graphRange: {
    default: [0, 20],
    type: Array
  },
  maxRange: {
    default: 40,
    type: Number
  },
  diagramLenList: {
    default: () => [],
    type: Array
  },
  dataGraph: {
    default: () => [],
    type: Array
  },
  linksGraph: {
    default: () => [],
    type: Array
  },
  deepLinks: {
    default: () => [],
    type: Array
  },
  loadingNetWork: {
    type: Boolean,
    default: false
  },
  noDataFlag: {
    type: Boolean,
    default: true
  }
})
const {diagramLenList, graphRange, dataGraph, linksGraph, maxRange, noDataFlag, loadingNetWork} = toRefs(props);
const echartoptVt = new Date().valueOf();
const graphCanvas = ref(null);
const controlSto = controlStore();
// let linksList = cloneDeep(linksGraph)
let _linksList = cloneDeep(linksGraph) //保持不变的数据
let _dataList = cloneDeep(dataGraph);
const chartOpt = computed(() => {
	let option = {
    grid: {
      top: 0,
    },
		tooltip: {},
		toolbox: {
			show: true,
		},
    lineStyle: {
      color: "#138848",
      width: 2
    },
		series: [
					{
							name: '',
							type: 'graph',
							layout: 'none',
							data: _dataList.value,
							links: _linksList.value,
							roam: true,
							label: {
									show: true,
									position: 'right',
									formatter: '{b}'
							},
							labelLayout: {
									hideOverlap: true
							},
							scaleLimit: {
									min: 0.4,
									max: 2
							},
							lineStyle: {
									color: 'source',
									curveness: 0.3
							}
					}
		]
	};

	return option;
});
const emitter = defineEmits(['changeShow', 'changeSlider'])
const changeSlider = (e) => {
  emitter('changeSlider', e)

}

const dowmImage = () => {
  // const canvas = document.querySelector('#uiCahrt canvas');
  // saveImageWithWhiteBackground(canvas)
  // saveImgDiv('uiCahrt')
  const elementToCapture = document.getElementById('uiCahrt');
      // 使用 HTML2Canvas 渲染为 Canvas
      html2canvas(elementToCapture).then(canvas => {
        // 创建一个链接 (blob) 来下载 Canvas 图片
        const link = document.createElement('a');
        link.href = canvas.toDataURL('image/png');
        link.download = 'Heatmap.png';

        // 触发点击事件来下载图片
        link.click();
      });
}
const changeShow = (item, index) => {
  item.isShow = !item.isShow;
  const isShow = item.isShow
  changelen(item)
  emitter('changeShow', item, index, isShow)
}
//取消某种关系的线
// let deleList = ref([]);
// let clkNum = 0;
let tArr = [];
const changelen = (item) => {
  let linksListlen = cloneDeep(linksGraph)
  let nodesCopy = cloneDeep(dataGraph)
  let arr = [];
  let id1 = [];
  let id2 = [];
  let arrdele = [];
  // console.log(linksListlen, '_dataList=====')
  // clkNum ++;
  // console.log(dataGraph.value, '-----00000')
  dataGraph.value.forEach(v => {
    if (item.source.code == v.category) {
      id1.push(v.id);
    }
    if (item.target.code == v.category) {
      id2.push(v.id);
    }
  })
  if(id1.length && id2.length) {
    id1.forEach(t => {
      id2.forEach(k => {
        if(item.isShow) {
          // linksListlen.value = [...new Set(deepLinks.value.concat(tArr))];
          // clkNum == 2 ? linksListlen.value = deepLinks.value.concat(tArr) : '';
          linksListlen.value.forEach(m => {
            if (m.source == t && m.target == k && Number(m.distance) >= graphRange.value[0] && Number(m.distance) <= graphRange.value[1]) {
              arr.push(m)
            }
          })
        } else {
          chartOpt.value.series[0].links.forEach((m, index) => {
            if (m.source == t && m.target == k) {
              // if (clkNum == 1) tArr.push(m)
              // tArr.push(m)
              // tArr = [...new Set(tArr)];
              chartOpt.value.series[0].links.splice(index, 1)
            }
          })
        }
      })
    })
  }
  // deleList.value = arrdele;
  changeYs(1)
  chartOpt.value.series[0].links = [...new Set([ ...chartOpt.value.series[0].links, ...arr])];
  graphCanvas.value ? graphCanvas.value.initEchart() : '';
}
//取消graph上的元素
const changeYs = (type, arr) => {
  let categoryShow = []
  let arrNodesShow = []
  if (type == 1) {
    diagramLenList.value.forEach(item => {
      if(item.isShow) {
        categoryShow = [...categoryShow, item.source.code, item.target.code]
      }
    })
    let nodeCopy = cloneDeep(dataGraph);
    nodeCopy.value.forEach(v => {
      if(categoryShow.includes(v.category)) {
        arrNodesShow.push(v);
      }
    })
  } else {
    // arr.forEach(o => {
    //   categoryShow = [...categoryShow, o.source, o.target]
    // })
    let nodeCopy = cloneDeep(dataGraph);
    let categoryArr = [];
    diagramLenList.value.forEach(e => {
      if(e.isShow) {
        categoryArr.push(e.source.code)
        categoryArr.push(e.target.code)
      }
    })
    categoryArr = [...new Set(categoryArr)]
    nodeCopy.value.forEach(v => {
      if(categoryArr.includes(v.category)) {
        arrNodesShow.push(v);
      }
    })
    // nodeCopy.value.forEach(v => {
    //   if(categoryShow.includes(v.id)) {
    //     arrNodesShow.push(v);
    //   }
    // })
  }
  
  chartOpt.value.series[0].data = arrNodesShow;
  graphCanvas.value ? graphCanvas.value.initEchart() : ''
}
watch(() => graphRange.value, (nv, ov) => {
  let linksListBar = [..._linksList.value]
  let arr = []
  linksGraph.value.forEach((e, index) => {
    if(Number(e.distance) >= nv[0] && Number(e.distance) <= nv[1]) {
      diagramLenList.value.forEach(v => {
        if (v.isShow) {
          if (e.sourceCategory == v.source.code && e.targetCategory == v.target.code) {
            arr.push(e);
          }
        }
      })
    }
  })
  chartOpt.value.series[0].links = arr;
  changeYs(2, arr)
  graphCanvas.value ? graphCanvas.value.initEchart() : ''
})
// watch(() => [linksGraph.value, dataGraph.value], (n, v) => {
//   chartOpt.value.series[0].links = n[0];
//   chartOpt.value.series[0].data = n[1];
//   graphCanvas.value ? graphCanvas.value.initEchart() : ''
// })

watch(() => maxRange.value, (n,v) => {
  graphCanvas.value ? graphCanvas.value.initEchart() : ''
})



</script>

<style scoped lang="scss">
.relate-dragram-box {
    display: flex;
    .dragram-item {
      width: 100%;
      // .range-box {
      //     width: 70%;
      //   }
      .dragram-item-top {
        // display: flex;
        // justify-content: space-between;
        position: relative;
        width: 100%;
        // height: 40px;
      }
      .range-box {
        width: calc(100% - 375px);
        min-width: calc(100% - 500px);
      }
      .chart-network {
          width: 600px;
          min-width: 500px;
          height: 360px;
      }
      .dragram-item-bott {
        display: flex;
        padding-top: 32px;
        align-content: space-between;
        .dragram-chart {
          height: 360px;
          width: 80%;
          .no-data-box {
            width: 100%;
            height: 264px;
            text-align: center;
            position: relative;
            img {
                margin-top: 20px;
            }
            .no-data-txt {
                font-family: PingFangSC, PingFang SC;
                font-weight: 400;
                font-size: 14px;
                color: #BC9F77;
                line-height: 20px;
                text-align: center;
                font-style: normal;
                position: absolute;
                width: 100%;
                bottom: 60px;
            }
          }
        }
        .dragram-legend {
          width: 375px;
          max-width: 500px;
          background: #FAFAFA;
          padding: 32px;
          .legen-list {
            .legen-item-dis {
              opacity: 0.2;
            }
            .legen-item {
              display: flex;
              padding: 8px 0;
              cursor: pointer;
              .legen-item-ltImg {
                width: 24px;
                height: 25px;
              }
              .legen-item-wz {
                font-family: PingFangSC, PingFang SC;
                font-weight: 600;
                font-size: 18px;
                color: #138848;
                line-height: 25px;
                font-style: normal;
              }
              .col1 {
                color: #BC9F77
              }
              .col2 {
                color: #138848
              }
              .col3 {
                color: #1677FF;
              }
              .col4 {
                color: #02BCD5;
              }
              .legen-center {
                margin: 0 8px;
                line-height: 25px;
              }
            }
          }
        }
      }
      .load-cont-box {
        // width: 375px;
        // max-width: 500px;
        // padding: 0 32px;
        // position: relative;
        text-align: right;
        .load-cont {
          // display: -webkit-inline-box;
          width: 44px;
          height: 32px;
          padding: 0 6px 0 8px;
          line-height: 32px;
          text-align: center;
          border: 1px solid #BC9F77;
          border-radius: 4px;
          color: #BC9F77;
          user-select: none;
          position: absolute;
          right: 0;
          cursor: pointer;
          &:hover {
              color: #E6C896;
              .hover-img {
                  display: inline-block;
              }
              .show-img, .active-img {
                  display: none;
              }
          }
          &:active {
              color: #967846;
              .active-img {
                  display: inline-block;
              }
              .hover-img, .show-img {
                  display: none;
              }
          }
          .hover-img, .active-img {
              display: none;
          }
          .img-wrap {
              position: relative;
              display: inline-block;
              top: 2px;
              .load-img {
                  height: 16px;
              }
          }
          .arrow-box {
              padding-left: 6px;
          }
        }
      }
      
    }
  }
</style>

<style lang="scss">
  .range-box {
    .el-slider__runway {
      background: #FFFFFF;
      height: 32px;
      position: relative;
      border: 1px solid #D2DBEE;
      .el-slider__bar {
        background: rgba(48, 115, 250, 0.1);
        height: 34px;
        position: absolute;
        // top: -8px;
      }
      .el-slider__button-wrapper {
        margin-top: 13px;
        .el-slider__button {
          width: 7px;
          height: 20px;
          background: #FFFFFF;
          border-radius: 2px;
          border: 1px solid #ACB8D1;
        }
      }
    }
  }
</style>